package com.lagou.rpc.consumer.controller;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import com.lagou.rpc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * 用户控制类
 */
@RestController
@RequestMapping("/user")
public class UserController {

//    @RpcReference
//    IUserService userService;

    @Autowired
    RpcClientProxy rpcClientProxy;

    @RequestMapping("/user/{id}")
    @ResponseBody
    public String getUserById(@PathVariable("id") Integer  id) throws InterruptedException {
//        return userService.getById(id);

        IUserService userService = (IUserService) rpcClientProxy.choseAndStartSever(IUserService.class);
        if (userService == null){
            return "抱歉，暂时没有任何服务端在线，客户端无法访问服务端";
        }
        //获取当前被选择调用的服务端IP
        String choseServer = rpcClientProxy.getChoseServer();
        //响应耗时计时开始
        long start = System.currentTimeMillis();
        Thread.sleep(new Random().nextInt(1000));
        //客户端通过RPC框架请求服务端业务实现
        User user = userService.getById(id);
        //响应耗时计时结束
        long end = System.currentTimeMillis();
        //当前被选择调用的服务端IP及对应的响应耗时封装到rpcClientProxy容器
        rpcClientProxy.getServerTimeMap().put(choseServer,end-start);
        System.out.println(user+"调用耗时情况：" + rpcClientProxy.getServerTimeMap().toString());
        return user.toString() + ",调用耗时：" + rpcClientProxy.getServerTimeMap().toString();
    }
}
